import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
    selector: 'app-countdown',
    template: `
    <nz-progress
        *ngIf='time!=0'
      nzType="circle"
      [nzFormat]='content'
      [nzPercent]="percent"
      [nzStrokeColor]="{ '0%': '#108ee9', '50%': '#2db7f5', '100%': '#87d068' }"
    ></nz-progress>
    <nz-progress
        *ngIf='time==0'
        nzType="dashboard"
        [nzPercent]="100"
        [nzStrokeColor]="{ '0%': '#108ee9', '100%': '#87d068' }"
    ></nz-progress>
    <ng-template #content>{{hour+':'+minute+':'+second}}</ng-template>
  `,
    styles: [
        `
      .ant-progress {
        margin-right: 8px;
        margin-bottom: 8px;
        display: inline-block;
      }
    `
    ],
    encapsulation: ViewEncapsulation.None
})
export class CountdownComponent implements OnInit{

    @Input()
    time = 0;
    percent = 100;
    hour: string | number = '00';
    minute: string | number = '00';
    second: string | number = '00';

    ngOnInit(): void {
        this.time = this.time * 60;
        const orignalTime = this.time;
        const interval = setInterval(() => {
            if (this.time === 0) {
                clearInterval(interval);
            }else {
                this.time--;
                this.percent = this.time * 100 / orignalTime;
                this.formateTime(this.time);
            }
        }, 1000);
    }

    formateTime(time) {
        const h = parseInt(String(time / 3600), 10);
        const minute = parseInt(String(time / 60 % 60), 10);
        const second = Math.ceil(time % 60);

        const hours = h < 10 ? '0' + h : h;
        const formatSecond = second > 59 ? 59 : second;
        this.hour = hours > 0 ? hours : '00';
        this.minute = minute < 10 ? '0' + minute : minute;
        this.second = formatSecond < 10 ? '0' + formatSecond : formatSecond;
    }


}
